import Vue from 'vue'
import VueRouter from 'vue-router'
//引入仓库
import store from './../store'
Vue.use(VueRouter)
//备份VueRouter.prototype原有的push|replace方法
let originPush = VueRouter.prototype.push;
let originReplace = VueRouter.prototype.replace;
//重写VueRouter.prototype的push方法
VueRouter.prototype.push = function (location, resolve, reject) {
     if (resolve && reject) {
          originPush.call(this, location, resolve, reject);
     } else {
          //第二种情况：外部在使用push方法的时候没有传递成功与失败的回调函数
          originPush.call(this, location, () => { }, () => { });
     }
}
//重写VueRouter.prototype.replace方法
VueRouter.prototype.replace = function (location, resolve, reject) {
     (resolve && reject) ? originReplace.call(this, location, resolve, reject) : originReplace.call(this, location, () => { }, () => { });
}
//引入路由
import routes from './routes'
const router =  new VueRouter({
    routes,
})
//全局路由守卫处
router.beforeEach((to,from,next)=>{
     let token = localStorage.getItem('user')
     let userInfo = localStorage.getItem('userInfo')
     if(token){
          //判断是否取login
          if(to.path == '/login'){
               // alert('您已登录')
               // next('/home')
          }else{
               //此处应判断是否有用户信息
               if(userInfo){
                   next() 
               }else{
                    //没有用户信息,但是有token
                    //需要清除掉已存储的token信息,并携带页面信息跳转至登录页
                    //此处判断不甚全面,完成后再补全
                    store.dispatch('clearToken')
                    next('/login?redirect'+to.path)
               }   
          }
          // next()
     }else{
          //没有token
          //需要跳转至login页面
          if(to.path != '/login'){
               next('/login')
          }else{
               next()
          }
     //    next()  
     }
})
export default router